<script lang="ts">
  import { invalidateAll } from "$app/navigation";
  import { onMount } from "svelte";
  import { libraryClient } from "../../../stores/library";
  import type { PageData } from "./$types";
  import type { LibraryBook } from "../../../bindings";
  import { writable } from "svelte/store";
  import { Button } from "$lib/components/ui/button";

  export let data: PageData;
  let book: LibraryBook;
  let pageTitle: string;

  $: pageTitle = `"${book?.title}" by ${book?.author_list.join(", ")}`;

  let metadata = writable<LibraryBook>({} as LibraryBook);

  const getBookMatchingId = async (
    id: LibraryBook["id"]
  ): Promise<LibraryBook> => {
    return (await libraryClient().listBooks()).filter(
      (book) => book.id.toString() === id
    )[0];
  };

  const x = async (id: string) => {
    book = await getBookMatchingId(id);
    metadata.set(book);
  };

  onMount(async () => {
    await x(data.id);
  });

  const save = async (event: SubmitEvent) => {
    event.preventDefault();
    const formData = new FormData(event.currentTarget as HTMLFormElement);

    libraryClient().updateBook(book!.id.toString(), {
      title: (formData.get("title") as string | undefined) ?? book.title ?? "",
    });
    invalidateAll();
    x(data.id);
  };
</script>

<div class="safeAreaView">
  {#if window.__TAURI__}
  <button on:click={() => history.back()}>X</button>
  <h1>Editing {pageTitle}</h1>

  <form on:submit={save}>
    <fieldset>
      <label for="title">Title</label>
      <input type="text" id="title" name="title" value={book?.title} />

      <label for="sortable_title">Sort title</label>
      <input
        disabled
        type="text"
        id="sortable_title"
        name="sortable_title"
        value={book?.sortable_title}
      />
      <span class="text-label-small">Sort fields are set automatically.</span>
    </fieldset>
    <fieldset>
      <label for="authors">Authors</label>
      <input
        disabled
        type="text"
        id="authors"
        name="authors"
        value={book?.author_list.join(", ")}
      />

      <label for="sortable_authors">Sort authors</label>
      <input
        disabled
        type="text"
        id="sortable_authors"
        name="sortable_authors"
        value={Object.entries(book?.author_sort_lookup ?? {})
          .map(([author, sorted]) => sorted)
          .join(", ")}
      />
      <span class="text-label-small">Sort fields are set automatically.</span>
    </fieldset>

    <button type="submit">Save</button>
  </form>
  {:else}
    <p>You cannot edit book metadata outside of the Citadel desktop app. For now!</p>

    <Button><a href="/">go home</a></Button>
  {/if}
</div>

<style>
  h1 {
    font-size: 1rem;
  }
  .safeAreaView {
    margin-top: 48px;
  }

  form,
  fieldset {
    display: flex;
    flex-direction: column;
  }

  .text-label-small {
    font-size: 0.8rem;
    font-style: italic;
    margin-top: 4px;
    margin-left: 4px;
  }
</style>
